﻿

import Request from "../../base/request.js?t=202511041006"
import Storage from "../../base/storage.js?t=202511041006"
import { imageBaseUrl, downloadfun, isImageFile, queryURLParams, easyCopy, getBrowserInfo } from "../../base/utils.js?t=202511041006"
const Composition = (proxy) => {

    const generateh = (text, isShort) => {
        if (isShort) {
            return h('div', {
                style: "width:100px;overflow:hidden;white-space: nowrap;text-overflow: ellipsis; -o-text-overflow: ellipsis;cursor:pointer"
            }, { default: () => text })
        } else {
            return h('div', {
                style: "width:300px;height:auto;"
            }, { default: () => text })
        }

    }

    const data = reactive({
        pdfOpen: false,
        pdfurl: "",

        areaList: [
            { label: '浦东', value: 1 },
            { label: '大场', value: 2 },
        ],

        checkPersonList: [

        ],

        messageTest: "",
        proxy: "",
        popShow: false,
        popTitle: '',
        imgUrl: "",
        previewShow: false,
        detailColumns: [
            {
                title: '序号',
                dataIndex: 'no',
                key: 'no',
                align: 'center',
                width: 80,
                customRender: ({ index }) => {
                    return (params.detailPagination.value.current - 1) * params.detailPagination.value.pageSize + index + 1
                },
            },
            {
                title: '姓名',
                dataIndex: 'name',
                key: 'name',
                align: 'center',
                customRender: ({ record }) => {
                    return `${record.name}(${record.code})`
                },


            },

            {
                title: '申请数量',
                dataIndex: 'number',
                key: 'number',
                align: 'center',

            },
            {
                title: '操作',
                dataIndex: 'StatusName',
                key: 'StatusName',
                align: 'center',
                width: '100px',
                customRender: ({ record, text }) => {
                    return h(antd.Button, {
                        color: "red",
                        onClick: () => {
                            methods.handleDeleteItem(record.code)
                        },
                        style: 'cursor:pointer'
                    }, { default: () => '删除' });
                },

            }
        ],
        detailDataSource: [],
        editInfoOptions: [],
        detailPagination: {
            total: 0,
            current: 1,
            loading: false,
            pageSize: 10,
            showTotal: total => `总共 ${total} 项`,
            defaultPageSize: 10,
            showSizeChanger: true, // 是否显示pagesize选择
            showQuickJumper: false, // 是否显示跳转窗
        },
        TypeId: null,
        editInfo: [{
        
            a: null,
            b: null,
            c: null,
            e: null,
            ceditInfoOptions: {},
            EmployeeList:[]
     
        }],
        cindex: 0,
        templateOpen: false,
        opType:0,
        uploadImg: {
            previewVisible: false,
            previewImage: "",
            previewTitle: "",
            fileList: [

            ]
        },
        itemRender: (data) => {

            let uid = data.file.uid
            const previewBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnPreview(uid) }, src: "../Bussiness/img/svg/preview.svg", width: 20, height: 22 }, { default: () => '预览' })
            const downloadBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnDownLoad(uid) }, src: "../Bussiness/img/svg/download.svg", width: 20, height: 22 }, { default: () => '下载' })
            const deleteBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnDelete(uid) }, src: "../Bussiness/img/svg/delete.svg", width: 18, height: 22 }, { default: () => '删除' })
            var btns = ""


            if (isImageFile(data.file.url)) {


                btns = h('div', { style: "display:flex;margin-left:10px" }, {
                    default: () => [
                        previewBtn,
                        downloadBtn,
                        deleteBtn
                    ]
                })

            } else {


                btns = h('div', { style: "display:flex;margin-left:10px" }, {
                    default: () => [
                        downloadBtn,
                        deleteBtn
                    ]
                })
            }

            return h('div', { style: 'margin-top:10px; width:400px;align-items:center; display:flex;justify-content:space-between' }, {
                default: () => [
                    data.file.name, btns
                ]
            })

        },
        addParams: {
            name: null,
            code: null,
            number: null,
        },
        uploadLock:false,
        configData: {
            name1: "",
            name2: "",
            name3: "",
            name4: "",
            name5: "",
            FactoryAreaId: 1,
            checkPersonId:null
        },

    })
    let params = toRefs(data)
    const methods = {
        setVisible: (value) => {
            params.previewShow.value = value;
        },
        handleDeleteItem: (code) => {
            params.detailDataSource.value=params.detailDataSource.value.filter(e => e.code != code)
            params.editInfo.value[params.cindex.value].EmployeeList = params.editInfo.value[params.cindex.value].EmployeeList.filter(e => e.EmployeeNo != code)
            params.detailPagination.value.total = params.detailDataSource.value.length
            params.editInfo.value[params.cindex.value].e = methods.sumData(params.editInfo.value[params.cindex.value].EmployeeList)
        },
        clearData: () => {
            params.detailDataSource.value = []
            params.detailPagination.value.total = 0
            params.editInfo.value[params.cindex.value].EmployeeList = params.detailDataSource.value
            params.editInfo.value[params.cindex.value].e = 0
        },
        btnPreview: (e) => {
            let item = params.uploadImg.value.fileList.find(es => es.uid == e)
            item.url = item.FilePath || item.url
            if (item.url.indexOf('.pdf') != -1) {
                params.pdfurl.value = item.url
                params.pdfOpen.value = true
            } else {
                params.imgUrl.value = item.url
                methods.setVisible(true)
            }
        },
        btnDownLoad: (e) => {
            let item = params.uploadImg.value.fileList.find(es => es.uid == e)
            item.url = item.FilePath || item.url
            const { name, url } = item
            params.uploadLock.value = true
            downloadfun(name, url).finally(() => {
                params.uploadLock.value = false

            })

        },
        btnDelete: (e) => {
            params.uploadImg.value.fileList = params.uploadImg.value.fileList.filter(es => es.uid != e)
        },
        handleChange: (info) => {

            if (!params.uploadLock.value) {
                params.uploadLock.value = true
                let formData = new FormData();
                formData.append('nfile', info.file.originFileObj)
                formData.append('uid', info.file.originFileObj.uid)
                Request({
                    url: "/download/uploadfile?Path=PPE/Apply",
                    method: 'post',
                    data: formData
                }).then(res => {
                        
                    let item = params.uploadImg.value.fileList.find(e => e.uid == res.Data[0].uid)
                    item.url = imageBaseUrl + res.Data[0].FilePath.split('../..')[1]
                    item.FileId = res.Data[0].FileId
                    item.FileName = res.Data[0].FileName
                    item.name = res.Data[0].FileName
                    params.uploadLock.value = false


                })
            }

         

        },

        handlePopOk: () => {

            if (params.opType.value == 0) {

                params.editInfo.value[params.cindex.value].EmployeeList.push({
                    EmployeeNo: params.addParams.value.code,
                    EmployeeName: params.addParams.value.name,
                    Quantity: params.addParams.value.number,
                })
                params.editInfo.value[params.cindex.value].e = methods.sumData(params.editInfo.value[params.cindex.value].EmployeeList)
                params.addParams.value = {
                    name: null,
                    code: null,
                    number: null
                }
            } else {

            }

            params.popShow.value = false
        },
        handleSTypeChange: (a, b, c) => {

            let label = params.editInfo.value[b].AttrList[c].ItemList.filter(es => es.Id == a)[0].AttributeValue
            params.editInfo.value[b].AttrList[c].SelectLabel = label
     

        },
        handleTypeChange: (c, d) => {

            let item = params.editInfoOptions.value.filter(e => e.value == d.a)[0]
            console.log(item,'item')
            let s = easyCopy(item) 
            delete s.Selected
        
            params.editInfo.value[c].alabel = item.label
            params.editInfo.value[c].b = item.img
            params.editInfo.value[c].c = item.unit
            params.editInfo.value[c].o = item.Description
            params.editInfo.value[c].p = item.Remark
            params.editInfo.value[c].e = item.rnum
            params.editInfo.value[c].AttrList = s.AttrList
            params.editInfo.value[c].EmployeeList = []
          

        },
        handleAdd: (i) => {
            params.opType.value = 0
            params.cindex.value = i
            params.popShow.value = true
            params.popTitle.value = `新增人员申请`
        },

        handleView: (e, i) => {

            if (!e.alabel || e.AttrList.filter(es => es.SelectLabel).length !== e.AttrList.length) {
                return params.messageTest.value.info('请先选择劳防用品和规格');
            }
            params.opType.value = 1
            params.popShow.value = true
            params.popTitle.value = `${e.alabel}(${e.AttrList.map(es => es.SelectLabel).join('/')})-人员申请详情`
            methods.getDetailTableList(true)
            params.cindex.value = i
        },

        addConfig: () => {
            params.editInfo.value.push({
                a: null,
                b: null,
                c: null,
                EmployeeList: [],
                ceditInfoOptions: {},
                e: null,
            })
        },
        delConfig: (i) => {
            params.editInfo.value.splice(i, 1)
        },
        filterOption: (val, type) => {
            return `${type.label}`.includes(`${val || ''}`)
        },
        handleCancel: () => {
            params.uploadImg.value.previewVisible = false;
            params.uploadImg.value.previewTitle = '';
        },
        getBase64: (file) => {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = () => resolve(reader.result);
                reader.onerror = error => reject(error);
            })
        },
        handlePreview: async (file) => {
            console.log(file, 'file')
            if (!file.url && !file.preview) {
                file.preview = (await methods.getBase64(file.originFileObj));
            }
            params.uploadImg.value.previewImage = file.url || file.preview;
            params.uploadImg.value.previewVisible = true;
            params.uploadImg.value.previewTitle = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
        },



        enter: (index) => {
            params.cindex.value = index
        },

        handleDetailTableChange: (page) => {
            const { current, pageSize } = page
            params.detailPagination.value.current = current;
            params.detailPagination.value.pageSize = pageSize;
            methods.getDetailTableList()
        },

        IGetDepartmentApproverList: () => {

            Request({
                url: "/PPE/GetDepartmentApproverList",
                method: 'post',

            }).then(res => {
                params.checkPersonList.value = res.Data.map(e => ({ label: e.UserName, value: e.UserNo }))
                if (params.checkPersonList.value.length != 0) {
                    params.configData.value.checkPersonId = params.checkPersonList.value[0].value
                }
            })
},
 
        getDetailTableList: (isRresh) => {
            params.detailPagination.value.loading = true
            if (isRresh) {
                params.detailPagination.value.current = 1
            }

            setTimeout(() => {
                params.detailDataSource.value = params.editInfo.value[params.cindex.value].EmployeeList.map(e => {
                    return {
                        name: e.EmployeeName,
                        code: e.EmployeeNo,
                        number: e.Quantity,

                    }
                })
                params.detailPagination.value.total = params.detailDataSource.value.length
                params.detailPagination.value.loading = false

            }, 300)

        },

        GetApplyFormNo: () => {
            Request({
                url: "/PPE/GetApplyFormNo",
                method: 'post',

            }).then(res => {
                params.configData.value.name1 = res.Data
            })

        },


        sumData: (Array, flag = true) => {

            let Sum = Array.reduce((Sum, currData) => {
                return Sum + currData.Quantity;
            }, 0)
  
            return Sum
        },

        importData: (i) => {
            const input = document.createElement('input');
            input.type = 'file';
            input.addEventListener('change', function (event) {
                const file = event.target.files[0];
                var formdata = new FormData()
                formdata.append('any',file)
                Request({
                    url: "/PPE/ImportEmpList",
                    method: 'post',
                    data: formdata
                }).then(res => {

                    params.messageTest.value.info(res.Msg);
                    params.editInfo.value[i].EmployeeList = [...params.editInfo.value[i].EmployeeList, ...res.Data]
                    params.editInfo.value[i].e = methods.sumData(params.editInfo.value[i].EmployeeList)

                })
            });
            input.click();
            
        },

        downloadTemplate: () => {
            downloadfun('人员申请模板', '../File/Templete/PPE/劳防用品申请人员导入模板.xls')
        },
        onBack: () => {
            window.location.href = `/PPE/SupplyRequest?TypeId=${params.TypeId.value}`
        },
        GetBasicList: () => {
            params.uploadLock.value = true
            Request({
                url: "/PPE/GetBasicList",
                method: 'post',
                data: {
                    TypeId: params.TypeId.value
                }
            }).then(res => {

                params.editInfoOptions.value = res.Data.map(e => {
                    return {
                        label: e.ProductName,
                        value: e.Id,
                        unit: e.Unit,
                        AttrList: e.AttrList,
                        rnum: 0,
                        Description: e.Description,
                        Remark: e.Remark,
                        img: e.ImagList && e.ImagList.map(es => {
                      return {
                        url: es.url ? es.url : imageBaseUrl + es.FilePath.split('../..')[1],
                        name: es.FileName,
                        uid: es.uid,
                        FileId: es.FileId
                            }
                     })
                    }
                })

            }).finally(() => {
                params.uploadLock.value = false
            })
        },
        onSubmit: (Status) => {

                if (params.editInfo.value.filter(e => e.a).length == 0) {
                    return params.messageTest.value.info('请选择劳防用品');
                }
                for (let list of params.editInfo.value) {

                    if (list.AttrList.filter(e => e.Selected).length != list.AttrList.length) {
                        return params.messageTest.value.info('请检查规格是否全部填写');
                    }
                }


                if (params.editInfo.value.filter(e => e.e == 0).length != 0) {
                    return params.messageTest.value.info('劳动用品申请数量不能为0');
                }

     
      
            let subOjb = {
                ApplyNo: params.configData.value.name1,
                Remark: params.configData.value.name5,
                Status: Status,
                FactoryAreaId: params.configData.value.FactoryAreaId,
                ApproveUser: params.configData.value.checkPersonId,
                TypeId: params.TypeId.value,
                FileList: params.uploadImg.value.fileList.map(e => e.FileId),
                BasicList: params.editInfo.value.map(e => {
                    return {
                        BasicId: e.a,
                        Quantity:e.e,
                        AttrItemsId: e.AttrList.map(es => es.Selected),
                        EmployeeList: e.EmployeeList,
                    }
                })
            }
            params.uploadLock.value=true
            

            Request({
                url: "/PPE/PPEApply",
                method: 'post',
                data: subOjb

            }).then(res => {
                params.messageTest.value.info(res.Msg);


                window.location.href = `/PPE/SupplyRequest?TypeId=${params.TypeId.value}`
            }).finally(() => {
                params.uploadLock.value = false
            })

        

  
        },
        init: () => {
              getBrowserInfo().catch(err => { console.log(err)})
            if (proxy) {
                params.proxy.value = proxy
            }
            const { message } = antd
            params.messageTest.value = message
            params.messageTest.value.config({
                top: `10vh`,
                duration: 7,
                maxCount: 1,
                rtl: true,
            });


            let info = Storage.get('AccountInfo', true)
            Request({
                url: "/Account/createJwtToken",
                method: 'post',
                data: {
                    "userName": info && info.UserNo
                }
            }).then(res => {
                methods.IGetDepartmentApproverList()
                let urlparams = queryURLParams()

                params.TypeId.value = urlparams.type
                Storage.set('token', res.Data,true)
                params.configData.value.name2 = `${info.UserName}(${info.UserNo})`
                params.configData.value.name3 =dayjs(Date.now()).format('YYYY-MM-DD HH:mm')
                params.configData.value.name4 = info.DepartmentName

                

                methods.GetApplyFormNo()
                methods.GetBasicList()


    
            })
        },
   
    }
    const template = {
        pdfPopModel: {
            template: `
           <a-modal v-model:open="pdfOpen" width = "80%" title = "PDF预览" v-on:ok="pdfOpen=false" >
<div style='height:700px'>
                <embed id="pdfviewscreen" :src="pdfurl" type="application/pdf" width="100%" style="height:100%;" />

</div>
  
            </a-modal >
`,
            setup() {
                return {
                    ...params,
                    ...methods,
                };
            }
        },




        bottomBtns: {
            template: `<div class="w-full bg-[#eeeeee] h-50  flex  items-center justify-end pr-4">
                    <a-space>


  <a-popconfirm
    title="确定执行此操作?"
    ok-text="确定"
    cancel-text="取消"
    @confirm="onSubmit(0)"
  >
 <a-button  :loading="uploadLock" type="dashed">保存</a-button>
  </a-popconfirm>

  <a-popconfirm
    title="确定执行此操作?"
    ok-text="确定"
    cancel-text="取消"
    @confirm="onSubmit(1)"
  >
          <a-button  :loading="uploadLock" type="primary">提交</a-button>
  </a-popconfirm>
                       
              
                        <a-button v-on:click="onBack" :loading="uploadLock">返回</a-button>
                    </a-space>
                </div>`,
            setup() {

                return {
                    ...params,
                    ...methods,
                };
            }

        }
    }
    return {
        ...params,
        ...methods,
        template
    }
}
export default Composition